<?php

namespace app\controller;

use app\model\Order;
use Carbon\Carbon;
use common\LogUtils;
use DateInterval;
use DateTime;
use plugin\admin\app\model\ActivatedCode;
use plugin\admin\app\model\Device;
use plugin\admin\app\model\Option;
use plugin\admin\app\model\PaySet;
use plugin\admin\app\model\Product;
use plugin\admin\app\model\User;
use support\Db;
use support\Request;

class IndexController
{
    public function index(Request $request)
    {
        $system = Option::where('name','system_config')->get();
        $systemInfo = json_decode($system,true);
        $systemValue = json_decode($systemInfo[0]['value'],true);
        $title = $systemValue['logo']['title'];
        $icon = $systemValue['logo']['image'];
        return view('index/index',['name' => $title,'icon'=>$icon]);
    }

    public function view(Request $request)
    {
        return view('index/view', ['name' => 'webman']);
    }
    public function about(Request $request)
    {
        return view('index/about', ['name' => 'webman']);
    }
    public function help(Request $request)
    {
        $system = Option::where('name','system_config')->get();
        $systemInfo = json_decode($system,true);
        $systemValue = json_decode($systemInfo[0]['value'],true);
        $title = $systemValue['logo']['title'];
        $icon = $systemValue['logo']['image'];
        return view('index/help', ['name' => $title,'icon'=>$icon]);
    }
    public function order(Request $request){
        if ($request->method()==="POST"){
            return json(['code' => 0, 'msg' => 'ok']);
        }
        return view('index/order');
    }

    public function query_product(Request $request){
        $pageSize = 8; // 每页显示的数量
        $currentPage = $request->post('page') ?? 1; // 获取当前页码，默认为第一页
        $start = ($currentPage - 1) * $pageSize; // 计算起始位置
//        $products = Db::table('wa_product')
//            ->orderBy('product_sort')
//            ->limit($pageSize)
//            ->offset($start)
//            ->get();
        $products = Product::skip($start)->take($pageSize)->orderBy('product_sort')->get();
        if (empty($products)){
            return json(['code' => 1, 'msg' => 'error']);
        }
        return json(['code' => 0, 'msg' => 'ok','data'=>$products]);
    }

    /**
     * 查询最近未支付订单的优惠金额 返回给前台一个不重复的优惠金额 以此来保证每个订单优惠金额不同 即最终支付金额不同
     * @return void
     */
    public function query_cut_price(Request $request){
        // 检查 session 数据是否存在
        $device_id = $request->post('device_id');
        if (!$device_id){
            $session = $request->session();
            $sessionToken = $session->get('token');
            if (!$sessionToken){
                return json(['code' => 100, 'msg' => '请重新登陆']);
            }else{
                $token = $request->post('token');
                LogUtils::info("输出服务器用户的sessionId：=".$sessionToken);
                LogUtils::info("输出客户端提交用户的sessionId：=".$token);
                if ($sessionToken!=$token){
                    return json(['code' => 100, 'msg' => 'token异常']);
                }
            }
        }
        $oneHourAgo = Carbon::now()->subHour();
        $unPayOrder =  \plugin\admin\app\model\Order::where('is_pay',0)
            ->where('created_at', '>=', $oneHourAgo)
            ->orderBy('created_at','desc')
            ->limit(50)
            ->select('product_name', 'pay_price','discount_price','is_pay')
            ->get();
        LogUtils::info($unPayOrder,"输出近一小时未支付订单");
        $cutPrice = [];
        for ($i = 0;$i<count($unPayOrder);$i++){
            $cutPrice[$i] = $unPayOrder[$i]['discount_price'];
        }
        LogUtils::info($cutPrice,"占用随机金额输出");
        do {
            $randomAmount = round(mt_rand(1, 99) / 100, 2); // 生成 0 到 1 的随机数，并保留两位小数
        } while (in_array($randomAmount, $cutPrice)); // 如果生成的金额已经在已占用的数组中，则重新生成
        LogUtils::info('最终输出的可用优惠金：'.$randomAmount);
        return json(['code' => 0, 'msg' => '优惠金额','data'=>$randomAmount]);
    }
    //创建订单
    public function create_order(Request $request){
        $device_id = $request->post('device_id');
        if (!$device_id){
            $session = $request->session();
            $sessionToken = $session->get('token');
            if (!$sessionToken){
                return json(['code' => 100, 'msg' => '请重新登陆']);
            }else{
                $token = $request->post('token');
                LogUtils::info("输出服务器用户的sessionId：=".$sessionToken);
                LogUtils::info("输出客户端提交用户的sessionId：=".$token);
                if ($sessionToken!=$token){
                    return json(['code' => 100, 'msg' => 'token异常']);
                }
            }
        }

        $order_no = $request->post('order_no');
        $product_id = $request->post('product_id');
        $product_name = $request->post('product_name');
        $pay_phone = $request->post('pay_phone');
        $pay_nickname = $request->post('pay_nickname');
        $is_pay = $request->post('is_pay');
        $pay_price = $request->post('pay_price');
        $discount_price = $request->post('discount_price');
        $username = $request->post('username');
        $user_id = $request->post('user_id');




        if (!empty($order_no)){
            $order = \plugin\admin\app\model\Order::where('order_no',$order_no)
                ->where('username',$username)
                ->first();
            $order->pay_nickname = $pay_nickname;
            $result = $order->update();
            if (!$result){//订单更新失败的同时先清理一下该账号下未支付订单
                return json(['code' => 1, 'msg' => '订单更新失败']);
            }
            return json(['code' => 0, 'msg' => '订单更新成功']);
        }
//        $orderOldUnpay = \plugin\admin\app\model\Order::where('username',$username)
//            ->where('is_pay',0)
//            ->whereNot('order_no',$order_no)
//            ->get();
//        LogUtils::info($orderOldUnpay,'该账号历史未支付订单删除');
//        LogUtils::info(is_array($orderOldUnpay),'是否是[]');
//        if ($orderOldUnpay->isEmpty()) {
//            LogUtils::info(true, '是否是[]');
//        } else {
//            LogUtils::info(false, '是否是[]');
//            // 遍历集合并删除订单
//            foreach ($orderOldUnpay as $order) {
//                $result = $order->delete();
//                LogUtils::info($order, '该账号历史未支付订单删除结果：=' . $result.' ');
//            }
//        }
        $user = User::where('username',$username)->first();
        LogUtils::info($user);
        if (empty($user)){
            return json(['code' => 2, 'msg' => '订单创建失败']);
        }
        if (empty($pay_price)){
            return json(['code' => 3, 'msg' => '订单创建失败']);
        }
        if (empty($discount_price)){
            return json(['code' => 4, 'msg' => '订单创建失败']);
        }

        $products = Product::where('id',$product_id)
            ->get();
//        $products = Db::table('wa_product')
//            ->where('id',$product_id)
//            ->orderBy('created_at','desc')
//            ->get();
        LogUtils::info($products);
        LogUtils::info('创建订单--'.' 商品查询长度 '.count($products));
        for ($i=0;$i<count($products);$i++){
           $everyProduct =  $products[$i];
           $currentProductPrice = $everyProduct->product_price;
           $currentProductId = $everyProduct->id;
           if ($product_id==$currentProductId){
               LogUtils::info("创建订单-当产品id相等时候 输出 该产品价格：".$currentProductPrice);
               LogUtils::info('创建订单-支付价格'.$pay_price.' 折扣价格 '.$discount_price.' 总价：'.($pay_price+$discount_price) . ' $currentProductPrice '.$currentProductPrice.' 输出价格比较结果');
               if ($currentProductPrice==($pay_price+$discount_price)){
                   if ($discount_price<=1){
                       $order = new Order();
                       $order_no = md5(sha1($pay_phone.$pay_nickname.$pay_price.time()));
                       $order->product_id = $product_id;
                       $order->product_name = $product_name;
                       $order->pay_phone = $pay_phone;
                       $order->pay_nickname = $pay_nickname;
                       $order->is_pay = $is_pay;
                       $order->pay_price = $pay_price;
                       $order->discount_price = $discount_price;
                       $order->order_no = $order_no;
                       $order->username = $username;
                       $order->user_id = $user_id;
                       $result = $order->save();
                       if (!$result){
                           return json(['code' => 1, 'msg' => '订单创建失败']);
                       }
                       return json(['code' => 0, 'msg' => 'success','data'=>$order_no]);
                   }else{
                       return json(['code' => 1, 'msg' => '订单创建失败']);
                   }
               }else{
                   return json(['code' => 1, 'msg' => '订单创建失败']);
               }
           }
        }
//        LogUtils::info($product_price ,'常见订单前输出该商品原价 111');
//        $result = $order->save();
//        if (!$result){
//            return json(['code' => 1, 'msg' => '订单创建失败']);
//        }
//        return json(['code' => 0, 'msg' => 'success','data'=>$order_no]);
        return json(['code' => 1, 'msg' => '订单创建失败']);
    }

    /**
     * 支付配置
     * @param Request $request
     * @return \support\Response|\think\response\Json
     */
    public function to_pay(Request $request){
//        $paySets = Db::table('wa_pay_set')->orderBy('created_at','desc')->limit(2)->get();
        $device_id = $request->post('device_id');
        LogUtils::info("device_id:=".$device_id);
        if (!$device_id){
            $session = $request->session();
            $sessionToken = $session->get('token');
            if (!$sessionToken){
                return json(['code' => 100, 'msg' => '请重新登陆']);
            }else{
                $token = $request->post('token');
                LogUtils::info("输出服务器用户的sessionId：=".$sessionToken);
                LogUtils::info("输出客户端提交用户的sessionId：=".$token);
                if ($sessionToken!=$token){
                    return json(['code' => 100, 'msg' => 'token异常']);
                }
            }
        }
        $paySets = PaySet::where('id','>',0)->orderBy('created_at','desc')->limit(2)->get();
        if (empty($paySets)){
            return json(['code' => 1, 'msg' => 'error']);
        }
        return json(['code' => 0, 'msg' => 'success','data'=>$paySets]);
    }

    /**
     * 移动端校验支付金额是否正确
     * @param Request $request
     * @return void
     */
    public function query_order(Request $request){
        $device_id = $request->post('device_id');
        $pay_nickname = $request->post('pay_nickname');
        LogUtils::info("deviceid:=".$device_id);
        if (empty($device_id)){//不是客户端提交的时候 去验证token
            $session = $request->session();
            $sessionToken = $session->get('token');
            if (!$sessionToken){
                return json(['code' => 100, 'msg' => '请重新登陆']);
            }else{
                $token = $request->post('token');
                LogUtils::info("输出服务器用户的sessionId：=".$sessionToken);
                LogUtils::info("输出客户端提交用户的sessionId：=".$token);
                if ($sessionToken!=$token){
                    return json(['code' => 100, 'msg' => 'token异常']);
                }
            }
        }
        $pay_price = $request->post('pay_price');
        $order = \plugin\admin\app\model\Order::where('pay_price',$pay_price)
            ->where('is_pay',0)
            ->where('pay_nickname',$pay_nickname)
            ->orderBy('created_at','desc')
            ->first();
        if (empty($order)){
            return json(['code' => 1, 'msg' => '查询订单失败']);
        }
        $order->is_pay = 1;
        //支付成功后直接查询激活码表根据product_id和激活码未被发送的状态 查出来之后直接将激活码发送状态改为已发送 ，并将该激活码赋值到对应订单表里
        $activatedCode = ActivatedCode::where('product_id',$order->product_id)
            ->where('product_activated_code_is_used',0)
            ->orderBy('created_at','desc')
            ->first();
        $activatedCode->product_activated_code_is_used = 1;
        $activatedCode->save();
        $order->activated_code = $activatedCode->product_activated_code;
        $result = $order->save();
        if (!$result){
            //如果订单更新失败，则该激活码状态重置为未发送
            $activatedCode -> product_activated_code_is_used = 0;
            $activatedCode->save();
            return json(['code' => 1, 'msg' => '订单更新失败']);
        }
        return json(['code' => 0, 'msg' => '订单更新成功','data'=>$order]);
    }

    /**
     * web 端查询自身已支付订单
     * @param Request $request
     * @return void
     */
    public function query_pay_over_order(Request $request){
        $device_id = $request->post('device_id');
        if (!$device_id){
            $session = $request->session();
            $sessionToken = $session->get('token');
            if (!$sessionToken){
                return json(['code' => 100, 'msg' => '请重新登陆']);
            }else{
                $token = $request->post('token');
//                LogUtils::info("输出服务器用户的sessionId：=".$sessionToken);
                LogUtils::info("用户的token：=".$token.' 服务器的token:'.$sessionToken);
                if ($sessionToken!=$token){
                    return json(['code' => 100, 'msg' => 'token异常']);
                }
            }
        }
        $pageSize = 5; // 每页显示的数量
        $currentPage = $request->post('page') ?? 1; // 获取当前页码，默认为第一页
        $start = ($currentPage - 1) * $pageSize; // 计算起始位置
        $user_id = $request->post('user_id');
        $order = Db::table('wa_order')
            ->where('user_id',$user_id)
            ->where('is_pay',1)
            ->orderBy('created_at','desc')
            ->limit($pageSize)->offset($start)
            ->get();
        if (empty($order)){
            return json(['code' => 1, 'msg' => '查询订单失败']);
        }
        return json(['code' => 0, 'msg' => '查询订单成功','data'=>$order]);
    }
}
